package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper mapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    //新增
    @Override
    public R add(Category category) {
        mapper.insert(category);
        return R.success("添加成功");
    }

    //分页查询
    @Override
    public R findPage(Integer page, Integer pageSize) {
        IPage<Category> p = new Page<>(page,pageSize);
        //按照正序的排序顺序
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);

        IPage<Category> selectPage = mapper.selectPage(p, wrapper);
        return R.success(selectPage);
    }

    //删除
    @Override
    public R removeById(Long id) {
        //判断要删除的分类下面是否还有菜品
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId,id);
        List<Dish> dishList = dishMapper.selectList(wrapper);
        if (dishList.size()>0){
            return R.error("此分类下存在菜品不能删除");
        }
        //判断要删除的分类下面是否还有套餐
        LambdaQueryWrapper<Setmeal> setmealwrapper= new LambdaQueryWrapper<>();
        setmealwrapper.eq(Setmeal::getCategoryId,id);
        List<Setmeal> setmealList = setmealMapper.selectList(setmealwrapper);
        if (setmealList.size()>0){
            return R.error("此分类下存在套餐不能删除");
        }

        mapper.deleteById(id);
        return R.success("删除成功");
    }
    //修改
    @Override
    public R updateById(Category category) {
        mapper.updateById(category);
        return R.success("修改成功");
    }
    //新增菜品时,回显菜品分类
    @Override
    public List<Category> list(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        if (type!=null){
            wrapper.eq(Category::getType,type);
        }
        List<Category> categoryList = mapper.selectList(wrapper);
        return categoryList;
    }
}
